package com.ds.common.mybatis.handle;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ds.common.exception.BizErrorEnum;
import com.ds.common.exception.BizException;
import com.ds.common.mybatis.core.domain.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;


@Slf4j
public class InjectionMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
                Date current = ObjectUtil.isNotNull(baseEntity.getCreateTime()) ? baseEntity.getCreateTime() : new Date();
                baseEntity.setCreateTime(current);
                baseEntity.setUpdateTime(current);
                baseEntity.setDeleted(0);
                baseEntity.setVersion(1);
                //if (ObjectUtil.isNull(baseEntity.getCreateBy())) {
                //    LoginUser loginUser = getLoginUser();
                //    if (ObjectUtil.isNotNull(loginUser)) {
                //        Long userId = loginUser.getUserId();
                //        // 当前已登录 且 创建人为空 则填充
                //        baseEntity.setCreateBy(userId);
                //        // 当前已登录 且 更新人为空 则填充
                //        baseEntity.setUpdateBy(userId);
                //        baseEntity.setCreateDept(ObjectUtil.isNotNull(baseEntity.getCreateDept())
                //                ? baseEntity.getCreateDept() : loginUser.getDeptId());
                //    }
                //}
            }
        } catch (Exception e) {
            throw new BizException("自动注入异常 => " + e.getMessage(), BizErrorEnum.HTTP_SERVER_ERROR);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
                Date current = new Date();
                // 更新时间填充(不管为不为空)
                baseEntity.setUpdateTime(current);
                // 当前已登录 更新人填充(不管为不为空)
                //Long userId = LoginHelper.getUserId();
                //if (ObjectUtil.isNotNull(userId)) {
                //    baseEntity.setUpdateBy(userId);
                //}

            }
        } catch (Exception e) {
            throw new BizException("自动注入异常 => " + e.getMessage(), BizErrorEnum.HTTP_SERVER_ERROR);
        }
    }

    /**
     * 获取登录用户名
     */
    //private LoginUser getLoginUser() {
    //    LoginUser loginUser;
    //    try {
    //        loginUser = LoginHelper.getLoginUser();
    //    } catch (Exception e) {
    //        log.warn("自动注入警告 => 用户未登录");
    //        return null;
    //    }
    //    return loginUser;
    //}

}
